﻿using System;
using System.Data.Linq;
using System.Linq;
using System.Web.UI.WebControls;
using Pariveda.DataAccess35.Business;

namespace Pariveda.DataAccess35.Web
{
    public partial class CustomerTiered : System.Web.UI.Page
    {
        #region Initialization
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                RefreshCustomerList();
            }
            ChangeConflictPanel.Visible = false;
            MessageLabel.Visible = false;
        }
        void RefreshCustomerList()
        {
            CustomerListBox.Items.Clear();
            CustomerListBox.Items.Add("-- Add New Customer --");
            CustomerListBox.Items.AddRange(new CustomerService().GetLookupList().Select(kvp => new ListItem(kvp.Value, kvp.Key.ToString())).ToArray());
            ShowCustomer();
        }
        void RefreshCustomerList(int customerId)
        {
            RefreshCustomerList();
            CustomerListBox.SelectedValue = customerId.ToString();
        }
        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            string customerXml = (string)ViewState["CustomerXml"];
            SelectedCustomer = SerializerUtil.Deserialize<Customer>(customerXml);
        }
        protected override object SaveViewState()
        {
            ViewState["CustomerXml"] = SelectedCustomer.Serialize();
            return base.SaveViewState();
        }
        #endregion

        #region Control Events
        protected void CustomerListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowCustomer();
        }
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            SaveCustomer(false);
        }
        protected void DeleteButton_Click(object sender, EventArgs e)
        {
            DeleteCustomer();
        }
        protected void YesDataChangeButton_Click(object sender, EventArgs e)
        {
            SaveCustomer(true);
        }
        protected void NoDataChangeButton_Click(object sender, EventArgs e)
        {
            ShowCustomer();
        }
        protected void CancelDataChangeButton_Click(object sender, EventArgs e)
        {
            ChangeConflictPanel.Visible = false;
        }
        protected void AddressRepeater_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Remove":
                    DeleteAddress(int.Parse((string)e.CommandArgument));
                    break;
            }
        }
        protected void AddAddressButton_Click(object sender, EventArgs e)
        {
            SaveAddressesLocally();
            SelectedCustomer.CustomerAddresses.Add(new CustomerAddress());
            RefreshAddresses();
        }
        #endregion

        #region Properties
        int? SelectedCustomerId
        {
            get { return CustomerListBox.SelectedIndex > 0 ? int.Parse(CustomerListBox.SelectedValue) : (int?)null; }
        }
        Customer SelectedCustomer
        {
            get;
            set;
        }
        #endregion

        /// <summary>
        /// Shows a status message on the screen
        /// </summary>
        /// <param name="message">The message to display</param>
        /// <param name="messageType">Type of the message (error or success)</param>
        void ShowMessage(string message, MessageType messageType)
        {
            MessageLabel.Text = message;
            switch (messageType)
            {
                case MessageType.Error:
                    MessageLabel.CssClass = "ErrorMessage";
                    break;
                case MessageType.Success:
                    MessageLabel.CssClass = "SuccessMessage";
                    break;
                default:
                    MessageLabel.CssClass = "Message";
                    break;
            }
            MessageLabel.Visible = true;
        }

        /// <summary>
        /// Shows the customer by setting the control values from the selected customer in the listbox
        /// </summary>
        void ShowCustomer()
        {
            CustomerService service = new CustomerService();
            ChangeConflictPanel.Visible = false;
            if (SelectedCustomerId.HasValue)
            {
                //Fill the controls
                SelectedCustomer = service.Get(SelectedCustomerId.Value, true);
                if (SelectedCustomer == null)
                {
                    RefreshCustomerList();
                    return;
                }
            }
            else
            {
                SelectedCustomer = new Customer();
            }
            NameTextBox.Text = SelectedCustomer.CompanyName;
            EmailTextBox.Text = SelectedCustomer.EmailAddress;
            FirstNameTextBox.Text = SelectedCustomer.FirstName;
            LastNameTextBox.Text = SelectedCustomer.LastName;
            RefreshAddresses();
        }

        /// <summary>
        /// Updates the address control with the value from the Selectedcustomer.CustomerAddresses property
        /// </summary>
        void RefreshAddresses()
        {
            if (SelectedCustomer != null)
            {
                AddressRepeater.DataSource = SelectedCustomer.CustomerAddresses;
            }
            else
            {
                AddressRepeater.DataSource = null;
            }
            AddressRepeater.DataBind();
        }

        /// <summary>
        /// Saves the customer to the database
        /// </summary>
        /// <param name="overwriteEdits">if set to <c>true</c> it will save even if the data has changed out from underneath</param>
        void SaveCustomer(bool overwriteEdits)
        {
            try
            {
                SelectedCustomer.CompanyName = NameTextBox.Text;
                SelectedCustomer.EmailAddress = EmailTextBox.Text;
                SelectedCustomer.FirstName = FirstNameTextBox.Text;
                SelectedCustomer.LastName = LastNameTextBox.Text;

                SaveAddressesLocally();

                CustomerService service = new CustomerService();
                service.Update(SelectedCustomer);
                RefreshCustomerList(SelectedCustomer.CustomerID);
                ShowCustomer();
                ShowMessage("Customer saved successfully", MessageType.Success);
            }
            catch (ChangeConflictException)
            {
                ChangeConflictPanel.Visible = true;
            }
        }

        /// <summary>
        /// Deletes the customer from the database
        /// </summary>
        void DeleteCustomer()
        {
            if (SelectedCustomer != null)
            {
                CustomerService service = new CustomerService();
                service.Delete(SelectedCustomer.CustomerID);
                RefreshCustomerList();
                ShowCustomer();
            }
        }

        /// <summary>
        /// Saves the address control values to the SelectedCustomer.CustomerAddresses
        /// </summary>
        void SaveAddressesLocally()
        {
            //if (AddressRepeater.SelectedIndex >= 0)
            for (int index = 0; index < AddressRepeater.Items.Count; index++)
            {
                ListViewItem item = AddressRepeater.Items[index];
                CustomerAddress address = SelectedCustomer.CustomerAddresses[index];

                DropDownList addressTypeDropDownList = (DropDownList)item.FindControl("AddressTypeDropDownList");
                TextBox addressLine1TextBox = (TextBox)item.FindControl("AddressLine1TextBox");
                TextBox addressLine2TextBox = (TextBox)item.FindControl("AddressLine2TextBox");
                TextBox cityTextBox = (TextBox)item.FindControl("CityTextBox");
                TextBox stateTextBox = (TextBox)item.FindControl("StateTextBox");
                TextBox postalCodeTextBox = (TextBox)item.FindControl("PostalCodeTextBox");

                address.AddressLine1 = addressLine1TextBox.Text;
                address.AddressLine2 = addressLine2TextBox.Text;
                address.City = cityTextBox.Text;
                address.StateProvince = stateTextBox.Text;
                address.PostalCode = postalCodeTextBox.Text;
            }
        }

        /// <summary>
        /// Deletes the address from the local SelectedCustomer.CustomerAddresses property
        /// </summary>
        /// <param name="index">The index.</param>
        void DeleteAddress(int index)
        {
            SaveAddressesLocally();
            CustomerAddress address = SelectedCustomer.CustomerAddresses[index];
            SelectedCustomer.CustomerAddresses.Remove(address);
            RefreshAddresses();
        }
    }
}
